var serverURL = "http://210.118.74.166:8080/agailgi_server";
var stateAjax = false; // 현재 ajax를 수행하는지 확인, 반복 통신 방지

function ajax( subURL, request, success )
{
	if( stateAjax == true )
		return;

	stateAjax = true;
	
	$.ajax({
		url : serverURL+subURL,
		type : 'post',
		dataType : "jsonp",
		jsonp : "callback",
		data : request,
		success : success,
		error : function(data, status, err) {
			var stateAjax = false;

			console.log("error forward : "+data);
	        alert('서버에 연결할 수 없습니다.');
		}
	})
}

function uploadFile( fileType, fileURI, subURL, request, success ) {
	if( stateAjax == true )
		return;
	stateAjax = true;
	
    server = serverURL + subURL;
			
	// Specify transfer options
    var options = new FileUploadOptions();
    options.fileKey="file";

	// jpg로 포맷 고정
    var filename = fileURI.substr( fileURI.lastIndexOf('/')+1 );
	var filenameArray = filename.split(".");
	if( fileType == 'image' ) {
	    filename = filenameArray[0]+".jpg";
		options.mimeType="image/jpeg";
	} else if ( fileType == 'video' ){
        filename = filenameArray[0]+".mp4";
		options.mimeType="video/mpeg";
	}

	options.fileName=filename;
    options.chunkedMode = false;
	options.params = request;

    var ft = new FileTransfer();
    ft.upload(fileURI, server, success, function(error) {
		alert("파일전송에 실패하였습니다.");
	}, options);
}

function loginToServer( userEmail, userPw )
{
	var subURL = "/Login";
	var request = "userEmail="+userEmail+"&userPw="+userPw;
	
	ajax( subURL, request, function(d){
			stateAjax = false;
			
			if( d.result == 1)
			{
				localStorage.setItem( 'userEmail', userEmail );
				localStorage.setItem( 'userPw', userPw );
				localStorage.setItem( 'userId', d.userinfo.userid );
				localStorage.setItem( 'userInfo', JSON.stringify(d.userinfo) );
				localStorage.setItem( 'mainbaby_growth', JSON.stringify(d.mainbaby_growth));
				localStorage.setItem( 'babyInfo', JSON.stringify(d.babyinfo) );
				
				// user부분에서는 있으나 main부분에서는 없음.
				nsUserInfo.userId = d.userinfo.userid;

				var babyInfo = d.babyinfo;

				$.each( babyInfo, function(i, item){
					if(item.is_main == "1") 
						localStorage.setItem( 'mainbaby_info', JSON.stringify(item) );
				});

				if( d.userinfo.num_of_baby > 0 || d.userinfo.isFamily==1 || d.userinfo.familyrequest==1 )
					location.href = "../agailgi/main_aga.html";
				else
					$.mobile.changePage("user_ready.html", {transition : 'slide'});	
			}
			else if( d.result == 2 )
			{
				alert("로그인에 실패하셨습니다.");
			}
		}
	)
}

function joinToServer( userEmail, userPw, userName, userGender )
{
	var subURL = "/Join";
	var request = "userEmail=" + userEmail + "&userPw=" + userPw + 
					"&userName=" + userName + "&userGender=" + userGender;

	ajax( subURL, request, function(d){
			stateAjax = false;
		
			if( d.result == 1 )
			{
				localStorage.setItem( 'userEmail', userEmail );
				localStorage.setItem( 'userPw', userPw );
				$.mobile.changePage("join_complete.html", {role : 'dialog'});
			}
			else if ( d.result == 3 )
			{
				$.mobile.changePage("join_fail.html", {role : 'dialog'});
			}
		}	
	)
}

function CreateRoomToServer( elementId, userId, numOfBaby, babyName, babyNick, birthday, babyGender )
{
	var subURL = "/CreateRoom";

	var fileURI = $("#"+elementId).css("background-image").substring( $("#"+elementId).css("background-image").indexOf('(')+1, $("#"+elementId).css("background-image").lastIndexOf(')'));	
    if (!fileURI) {
		alert("파일를 선택해주세요.");
        return;
    }
	
	// 생일 포맷 변경
    var tempBirthday = birthday.split('\/');
    tempBirthday = tempBirthday[2]+"-"+tempBirthday[0]+"-"+tempBirthday[1];

	var request = new Object();
    request.userId = userId;
    request.numOfBaby = numOfBaby;
    request.babyName = babyName;
    request.babyNick = babyNick;
    request.babyBirthday = tempBirthday;
    request.babyGender = babyGender;
      
	uploadFile( "image", fileURI, subURL, request, function( r ){
		stateAjax = false;
		
		var result = JSON.parse(r.response);
		// 로컬에 저장된 메인베이비정보를 수정할지 그대로 둘지, 그런 행위들
		// user.js에 정의되어있음.
		checkBaby(result.babyinfo); 
	});
}

function modifyRoomToServer( elementId, userId, numOfBaby, babyName, babyNick, birthday, babyGender )
{
	var subURL = "/ModifyProfile";

	var fileURI = $("#"+elementId).css("background-image").substring( $("#"+elementId).css("background-image").indexOf('(')+1, $("#"+elementId).css("background-image").lastIndexOf(')'));	
    if (!fileURI) {
		alert("파일를 선택해주세요.");
        return;
    }
	
	// 생일 포맷 변경
    var tempBirthday = birthday.split('\/');
    tempBirthday = tempBirthday[2]+"-"+tempBirthday[0]+"-"+tempBirthday[1];

	var request = new Object();
    request.userId = userId;
    request.numOfBaby = numOfBaby;
    request.babyName = babyName;
    request.babyNick = babyNick;
    request.babyBirthday = tempBirthday;
    request.babyGender = babyGender;
      
	uploadFile( "image", fileURI, subURL, request, function( r ){
		stateAjax = false;
		
		var result = JSON.parse(r.response);
		// 로컬에 저장된 메인베이비정보를 수정
		// profile/profile.js에 정의되어있음.
		changeLocalProfile(result.babyinfo); 
	});
}

function inviteParentToServer( inviteUserEmail, babyId )
{
	subURL = "/InviteParent";
	request = "userEmail=" + inviteUserEmail + "&babyId=" + babyId;

	ajax( subURL, request, function(d){
		stateAjax = false;
		
		if( d.result == 3 )
			alert("입력한 이메일을 가진 유저가 없습니다.");
		else
			location.href ="../agailgi/main_aga.html";
		
	})
}

function searchBabyToServer( userId, babyNick )
{
	subURL = "/SearchBaby";
	request = "userId=" + userId + "&babyNick="+babyNick;

	ajax(subURL, request, function(d){
		stateAjax = false;
		
		refreshBabyList( d.babyinfo, 0 ); // user.js
	});
}

// 추가버튼을 요청중으로 바꾸어주기 위해서 idx(index)를 받는다.
function requestFamilyToServer( userId, babyId, idx )
{
	subURL = "/BeFamily";
	request = "userId=" + userId + "&babyId="+ babyId;

	ajax( subURL, request, function(d){
		stateAjax = false;
		$(".list_btn_invite").eq(idx).css("background-image",'url(../images/list/btn_request_ing.png)');
	});
}

function requestPostToServer( userId, babyId, startIndex )
{
	subURL = "/BabyRoom";
	request = "userId=" + userId + "&babyId="+babyId + "&endPoint=" + startIndex;

	ajax( subURL, request, function(d){
		stateAjax = false;
		refreshPost(d.post, startIndex);
		refreshNewsBtn( d.news_exist );
	});
}

function requestSnsPostToServer( userId, babyId, startIndex )
{
	subURL = "/Sns";
	request = "userId=" + userId + "&babyId="+babyId + "&endPoint=" + startIndex;

	ajax( subURL, request, function(d){
		stateAjax = false;
		refreshSnsPost(d.post, startIndex);
		refreshNewsBtn( d.news_exist );
	});
}

function requestProfileToServer( userId, babyId )
{
	subURL = "/Profile";
	request = "userId=" + userId + "&babyId="+babyId;

	ajax( subURL, request, function(d){
		stateAjax = false;
		refreshNewsBtn( d.news_exist );
		refreshProfile( d, babyId );
	});
}
/*여기서 타입은 babyroom인지 sns인지 확인하는 인자*/
function sendReplyToServer( userId, postId, postUserId, contents, type )
{
	subURL = "/AddReply";
	request = "replyUserId="+userId+"&postId="+postId+"&postUserId="+postUserId+"&contents="+contents;

	ajax( subURL, request, function(d){
		stateAjax = false;

		if( type == 'babyroom')
			$.mobile.changePage("../main_aga.html",{transition:"slide"});
		else
			$.mobile.changePage("../main_sns.html",{transition:"slide"});	
	})
}

function requestDetailPostToServer( userId, detailPostId, type )
{
	subURL = "/Post";
	request = "userId=" + userId + "&postId="+detailPostId;
	
	ajax( subURL, request, function(d){
		stateAjax = false;

		if( type == 'babyroom' )
			refreshPost(d.post, 0);
		else if( type == 'sns' )
			refreshSnsPost(d.post, 0);

		refreshNewsBtn( d.news_exist );
	})
}

function requestChangeMainBabyToServer(userId, oldBabyId, newBabyId )
{
	subURL = "/ChangeMainbaby";
	request = "userid"+userId+"&oldBabyId="+oldBabyId+"&newBabyId="+newBabyId;

	ajax( subURL, request, function(d){
		stateAjax = false;
		$.each( user.babyInfo, function(i, item){
			if( item.babyid == newBabyId )
			{
				item.is_main = "1";
				user.mainbaby_info = item;
				profileInfo.init();
			}
			if( item.babyid == oldBabyId )
			{
				item.is_main = "0";
			}
		} );
		alert("메인 아이를 변경하였습니다.");			
	})
}	

function InviteFamilyToServer( myBabyId, toUserId, idx )
{
	subURL = "/InviteFamily";
	request = "babyId=" + myBabyId + "&userId=" + toUserId;

	ajax( subURL, request, function(d){
		stateAjax = false;
		$(".list_btn_invite_family").eq(idx).css("background-image",'url(../../images/list/btn_request_ing.png)');
	})
}

function acceptRequestNewsToServer( userId, newsId, index )
{
	subURL = "/AcceptRequest";
	request = "newsId=" + newsId;

	ajax( subURL, request, function(d){
		stateAjax = false;
		
		if( index < 5 )
		{
			requestNewsToServer( userId );
		}
		else
		{
			requestNewsToServer( userId );
			// 포스트를 요청
			// 하나만 요청
			// requestPost( d.postid );
		}
	})
}

function requestNewsToServer( userId )
{
	subURL = "/News";
	request = "userId="+userId;

	ajax( subURL, request, function(d){
		stateAjax = false;
		refreshNews( d.news );
	})
}

function requestDeleteFriendToServer( userId, babyId, delBabyId )
{
	subURL = "/DeleteFriend";
	request = "babyId=" + babyId + "&delBabyId="+delBabyId;

	ajax( subURL, request, function(d){
		stateAjax = false;
		requestFriendListToServer( userId, babyId );
	})
}

function requestFriendToServer( babyId, toBabyId, idx )
{
	subURL = "/BeFriend";
	request = "fromBabyId=" + babyId + "&toBabyId=" + toBabyId;

	ajax( subURL, request, function(d){
		stateAjax = false;
		if( idx != null )
			$(".list_btn_invite").eq(idx).css("background-image",'url(../../images/list/btn_request_ing.png)');
		alert("친구 요청 성공");
	})
}

function requestFriendListToServer( userId, babyId )
{
	subURL = "/Friendlist";
	request = "userId=" + userId + "&babyId="+babyId + "&endPoint=" + "0";

	ajax( subURL, request, function(d){
		stateAjax = false;
		refreshNewsBtn( d.news_exist );
		refreshFriendList(d.friend, 0);
	})
}

function requestDeleteFamilyToServer( userId, babyId, delUserId )
{
	subURL = "/DeleteFamily";
	request = "babyId="+babyId+"&delUserId="+delUserId;

	ajax( subURL, request, function(d){
		stateAjax = false;
		requestFamilyListToServer( userId, babyId );	
	});
}

function requestFamilyListToServer( userId, babyId )
{
	subURL = "/FamilyList";
	request = "userId=" + userId + "&babyId=" + babyId;

	ajax( subURL, request, function(d){
		stateAjax = false;
		refreshNewsBtn( d.news_exist );
		refreshFamilyList(d.family, 0);
	});
}

function requestSearchBabyWithBabyIdToServer(babyId, babyNick )
{
	subURL = "/SearchBabyWithBabyId";
	request = "babyId=" + babyId + "&babyNick=" + babyNick;

	ajax( subURL, request, function(d){
		stateAjax = false;
		refreshSearchBabyList( d.babyinfo, 0 )
	});
}

function reqeustSearchFamilyToServer( babyId, userEmail )
{
	subURL = "/SearchFamily";
	request = "babyId=" + babyId + "&userEmail="+userEmail;

	ajax( subURL, request, function(d){
		stateAjax = false;
		refreshSearchFamilyList( d.userinfo, 0 );
	});
}

function requestBabyListToServer( userId )
{
	subURL = "/BabyList";
	request = "userId="+userId;

	ajax( subURL, request, function(d){
		stateAjax = false;
		refreshNewsBtn( d.news_exist );
		refreshAgaList(d.baby);
	});
}

function requestWritePostToServer( userId, babyId)
{
	subURL = "/WritePost";
	request = "userId=" + userId + "&babyId=" + babyId + "&postTitle="+ diaryInfo.title + 
				"&postContents=" + diaryInfo.contents + "&postPerm="+ diaryInfo.permission + 
				"&diaryTypeId="+diaryInfo.typeId+"&diaryAmount="+diaryInfo.amount+	
				"&diaryStartTime="+diaryInfo.startTime+"&diaryEndTime="+diaryInfo.endTime+"&postDateTime="+diaryInfo.dateTime;

	ajax( subURL, request, function(d){
		stateAjax = false;

		user.mainbaby_growth.push(diaryInfo.typeId);
		$.mobile.changePage("../main_diary.html",{transition:'slide'});
	})
}

function writePostWithPhotoToServer( elementId, userId, babyId )
{
	var subURL = "/PostPhoto";

	var fileURI = $("#"+elementId).css("background-image").substring( $("#"+elementId).css("background-image").indexOf('(')+1, $("#"+elementId).css("background-image").lastIndexOf(')'));	
    if (!fileURI) {
		alert("파일를 선택해주세요.");
        return;
    }

	var request = new Object();
	request.userId = userId;
	request.babyId = babyId;
    request.postTitle = diaryInfo.title;
    request.postContents = diaryInfo.contents;
    request.postPerm = diaryInfo.permission;
    request.diaryTypeId = diaryInfo.typeId;
    request.diaryAmount = diaryInfo.amount;
    request.diaryStartTime = diaryInfo.startTime;
    request.diaryEndTime = diaryInfo.endTime;
    request.postDateTime = diaryInfo.dateTime;
      
	uploadFile( "image", fileURI, subURL, request, function( r ){
		stateAjax = false;
		
		alert("사진을 전송하였습니다.");
		postInfo.startIndex=0;
        $.mobile.changePage("../main_aga.html", {transition:'slide'});
	});
}

function writePostWithVideoToServer( userId, babyId )
{
	var subURL = "/PostMovie";
	var videoURI = $("#uploadVideoUrl").val();
    	
    if (!videoURI || videoURI == "") {
		alert("동영상을 올려주세요");
        return;
    }

	var request = new Object();
	request.userId = userId;
	request.babyId = babyId;
    request.postTitle = diaryInfo.title;
    request.postContents = diaryInfo.contents;
    request.postPerm = diaryInfo.permission;
    request.diaryTypeId = diaryInfo.typeId;
    request.diaryAmount = diaryInfo.amount;
    request.diaryStartTime = diaryInfo.startTime;
    request.diaryEndTime = diaryInfo.endTime;
    request.postDateTime = diaryInfo.dateTime;
      
	uploadFile( "video", fileURI, subURL, request, function( r ){
		stateAjax = false;
		alert("비디오 전송을 완료하였습니다.");
        $.mobile.changePage("../main_aga.html", {transition:'slide'});
	});
}

function updateRecommendFriendToServer( userId, babyId )
{
	subURL = "/Update";
	request = "userId="+userId+"&babyId="+babyId;

	ajax( subURL, request, function(d){
		stateAjax = false;
		$("#updateRecommendFriendText").html("약 몇초후에 업데이트됩니다.");
	});
}

function recommendFriendToServer( userId, babyId )
{
	subURL = "/RecommendFriend";
	request = "userId="+userId+"&babyId="+babyId;

	ajax( subURL, request, function(d){
		debug = d;
		stateAjax = false;
		refreshRecommendFriend( d.friend );
	});
}

function requestMessageBoxToServer( babyId )
{
	subURL = "/MessageBox";
	request = "babyId="+babyId;
	
	ajax( subURL, request, function(d){
		stateAjax = false;
		refreshMessageBox( d );
	})
}

function requestMessageToServer( myBabyId, toBabyId )
{
	subURL = "/Message";
	request = "babyId="+myBabyId+"&yourId=" + toBabyId;

	ajax( subURL, request, function(d){
		stateAjax = false;
		refreshMessage(d);
	})
}

function sendMessageToServer( userId, fromBabyId, toBabyId, contents )
{
	subURL = "/MessageSend";
	request = "fromUser="+userId+"&fromBaby="+fromBabyId+"&toBaby="+toBabyId+"&contents="+contents;

	ajax( subURL, request, function(d){
		stateAjax = false;
		alert("쪽지보내기 성공!!");
		$.mobile.changePage("../main_profile.html",{transition:'slide'});
	});
}